package com.ww.demo.thread.d5;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {

    private final static int THREAD_COUNT_NUM = 7;

    public static void main(String[] args) {

        CyclicBarrier callMasterBarrier = new CyclicBarrier(THREAD_COUNT_NUM, new Runnable() {
            @Override
            public void run() {
                System.out.println("7 法师已到齐，同时出发，收集龙珠!");
                summonDragon();
            }
        });

        for(int i = 1; i<= THREAD_COUNT_NUM; i++){
            int index = i;
            new Thread(() -> {
                System.out.println("召集第" + index + "个法师");
                try {
                    callMasterBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static void summonDragon(){
        CyclicBarrier summonDragonBarrier = new CyclicBarrier(THREAD_COUNT_NUM, new Runnable() {
            @Override
            public void run() {
                System.out.println("集齐七龙珠！");
            }
        });

        for (int i = 1; i <= THREAD_COUNT_NUM; i++){
            int index = i;
            new Thread(() -> {
                System.out.println("第" + index + "颗龙珠已收集到！");
                try {
                    summonDragonBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

}
